<?php
/*
 * Copyright 2009 Eat Local Food, LLC
 * Copyright (c) 2008 osCommerce (this file was written after
 * code review of osCommerce).
 *
 * This file is part of gwtCommerce.
 *
 * gwtCommerce is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * gwtCommerce is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with gwtCommerce.  If not, see <http://www.gnu.org/licenses/>.
 */

require_once('includes/functions/module_functions.php');
class plugnpay {

	// class constructor
	function plugnpay()
	{
		$this->module_key = 'MODULE_PAYMENT_PLUGNPAY';
		$this->code = 'plugnpay';
		$this->enabled = ((MODULE_PAYMENT_PLUGNPAY_STATUS == 'true') ? true : false);
		$this->sort_order = MODULE_PAYMENT_PLUGNPAY_SORT_ORDER;
		$this->status_id = MODULE_PAYMENT_PLUGNPAY_ORDER_STATUS_ID;
		$this->email_footer = false;
	}

	// class methods

	function confirm_zone($params, &$checkout_component)
	{
		return check_zone(MODULE_PAYMENT_PLUGNPAY_ZONE, $checkout_component->billTo['country_id'], $checkout_component->billTo['zone_id']);
	}

	function setup(&$params, &$checkout_component)
	{
		$setup['code'] = $this->code;
		$setup['payment_method'] = MODULE_PAYMENT_PLUGNPAY_PAYMETHOD;
		$setup['check_cvv'] = ((MODULE_PAYMENT_PLUGNPAY_CVV == 'yes') ? true : false);
		$setup['accepted_credit_cards'] = MODULE_PAYMENT_PLUGNPAY_ACCEPTED_CC;
		$setup['sort_order'] = $this->sort_order;

		return $setup;
	}

	function process(&$params, &$checkout_component)
	{
		$params['payment_method'] = MODULE_PAYMENT_PLUGNPAY_PAYMETHOD;

		$accountId = (int)$params['accountId'];

		unset($form_data);

		# start building submit array
		$form_data = array(
			publisher_name => MODULE_PAYMENT_PLUGNPAY_LOGIN,
			publisher_email => MODULE_PAYMENT_PLUGNPAY_PUBLISHER_EMAIL,
			mode => 'auth',
			convert => 'underscores',
			easycart => '1',
			shipinfo => '1',
			client => 'gwtCommerce_API',
			authtype => MODULE_PAYMENT_PLUGNPAY_CCMODE == 'authonly' ? 'authonly' : 'authpostauth',
			card_amount => number_format($checkout_component->cart_prices['ot_total']['value'] * $checkout_component->currency['value'], 2),
			currency => "{$checkout_component->currency['code']}",
			currency_value => "{$checkout_component->currency['value']}",
			dontsndmail => MODULE_PAYMENT_PLUGNPAY_DONTSNDMAIL == 'yes' ? 'yes': 'no',
			order_id => "$accountId",
			card_name => "{$checkout_component->billTo['name']}",
			card_company => "{$checkout_component->billTo['company']}",
			card_address1 => "{$checkout_component->billTo['street_address']}",
			card_city => "{$checkout_component->billTo['city']}",
			card_state => "{$checkout_component->billTo['state']}",
			card_zip => "{$checkout_component->billTo['postcode']}",
			card_country => "{$checkout_component->billTo['country']}",
			phone => "{$checkout_component->accountInfo['telephone']}",
			email => "{$checkout_component->accountInfo['email_address']}",
			shipname => "{$checkout_component->shipTo['name']}",
			company => "{$checkout_component->shipTo['company']}",	
			address1 => "{$checkout_component->shipTo['street_address']}",
			city => "{$checkout_component->shipTo['city']}",
			state => "{$checkout_component->shipTo['state']}",
			zip => "{$checkout_component->shipTo['postcode']}",
			country => "{$checkout_component->shipTo['country']}",
			ipaddress => "{$_SERVER['REMOTE_ADDR']}",
			sessionId => "{$params['accountSession']}"
		);

		$cart = &$checkout_component->cart;
		$sz = sizeof($cart);
		for ($i=0; $i< $sz; $i++)
		{
			$j = $i + 1;
			$form_data["item$j"] = $cart[$i]['model'];
			$form_data["cost$j"] = number_format($cart[$i]['cart_price'] * $checkout_component->currency['value'], 2);
			$form_data["quantity$j"] = $cart[$i]['cart_qty'];
			$form_data["description$j"] = $cart[$i]['name'];
		}

		$form_data["shipping"] = number_format($checkout_component->cart_prices['ot_shipping']['value'] * $checkout_component->currency['value'], 2);
		$form_data["tax"] = number_format($checkout_component->cart_prices['ot_tax']['value'] * $checkout_component->currency['value'], 2);

		if ((MODULE_PAYMENT_PLUGNPAY_PAYMETHOD == "onlinecheck") && ($HTTP_POST_VARS['plugnpay_paytype'] == 'echeck')) {
			// use electronic check info - TBD 
			/*
			$form_data['paymethod'] = 'onlinecheck';
			$form_data['accttype'] = $this->echeck_accttype;
			$form_data['accountnum'] = $this->echeck_accountnum;
			$form_data['routingnum'] = $this->echeck_routingnum;
			$form_data['checknum'] = $this->echeck_checknum;
			*/
		}
		else {
			// or assume credit card info
			$form_data['paymethod'] = 'credit';
			$form_data['card_name'] = $checkout_component->billTo['name'];
			$form_data['card_number'] = $checkout_component->billTo['creditCardNumber'];
			$card_exp = $checkout_component->billTo['creditCardExpirationMonth'] . substr($checkout_component->billTo['creditCardExpirationYear'], -2);
			$form_data['card_exp'] = $card_exp;
			if(MODULE_PAYMENT_PLUGNPAY_CVV == 'yes') {
				$form_data['card_cvv'] = $checkout_component->billTo['creditCardCVV'];
			}
		}

		if((MODULE_PAYMENT_PLUGNPAY_TESTMODE == 'Test') || (MODULE_PAYMENT_PLUGNPAY_TESTMODE == 'Test And Debug')) {
			$form_data['mode'] = 'debug';
		}
		
		$data='';
		// concatenate order information variables to $data
		while(list($key, $value) = each($form_data)) {
			$data .= $key . '=' . urlencode(preg_replace('/,/', '', $value)) . '&';
		}
	
		// take the last & out for the string
		$data = substr($data, 0, -1);

		/* Debug code - will dump cURL data to a file when
	 	* the admin module Transaction Mode is set to Test and Debug.
	 	* The file is written into the root directory of the catalog
	 	*/
        	if (MODULE_PAYMENT_PLUGNPAY_TESTMODE == 'Test And Debug') {
				$filename = './plugnpay_debug.txt';
				$fp = fopen($filename, "a");
				$write = fputs($fp, "Request Data: $data\n");
				fclose($fp);
        	}

		unset($response);

		$request = "https://pay1.plugnpay.com/payment/pnpremote.cgi";
		$session = curl_init();
		curl_setopt($session, CURLOPT_URL, $request);
       		curl_setopt($session, CURLOPT_HTTPPROXYTUNNEL, CURLOPT_HTTPPROXYTUNNEL_SETTING);
		if (CURLOPT_HTTPPROXYTUNNEL_SETTING == TRUE)
		{
			if (CURLOPT_PROXYTYPE_SETTING == 'CURLPROXY_SOCKS5') {
        			curl_setopt($session, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
			}
			else {
        			curl_setopt($session, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
			}
        		curl_setopt($session, CURLOPT_PROXY, CURLOPT_PROXY_SETTING);
		}
		curl_setopt($session, CURLOPT_SSL_VERIFYPEER, FALSE);
    		curl_setopt($session, CURLOPT_VERBOSE, 0);
    		curl_setopt($session, CURLOPT_POST, 1);
    		curl_setopt($session, CURLOPT_POSTFIELDS, $data);
    		curl_setopt($session, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt ($session, CURLOPT_TIMEOUT, 120);
		$authorize = curl_exec($session);
		curl_close($session);
		$response = preg_split("/,/", $authorize);

		/* Debug code - will dump cURL response to a file when
	 	* the admin module Transaction Mode is set to Test and Debug.
	 	* The file is written into the root directory of the catalog
	 	*/
		if (MODULE_PAYMENT_PLUGNPAY_TESTMODE == 'Test And Debug') {
			$filename = './plugnpay_debug.txt';
			$fp = fopen($filename, "a");
			$write = fputs($fp, "Response: $authorize\n\n");
			fclose($fp);
		}

		if ($response[0] == '')
		{
			$checkout_component->errorCode = -1;
			$checkout_component->errorMessage = 'Payment_' . $this->code . '_MissingResponse';
			return;
		}

		$FinalStatus = '';
		parse_str($response[0]);
		if ($FinalStatus != 'success')
		{
			$checkout_component->errorCode = -1;
			$checkout_component->errorMessage = 'Payment_' . $this->code . '_' . $FinalStatus;
			$checkout_component->paymentErrorMessage = $MErrMsg;

			if ($FinalStatus == null || $FinalStatus == '') {
				$checkout_component->errorMessage = 'Payment_' . $this->code . '_Unknown';
			}
		}
	}

	function check() {
		if (!isset($this->_check)) {
			$this->_check = check_module($this->module_key);
		}
		return $this->_check;
	}

	function install() {
		run_sql("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, configuration_values, date_added) values ('Enable PlugnPay Module', 'MODULE_PAYMENT_PLUGNPAY_STATUS', 'true', 'Do you want to accept payments through PlugnPay?', '6', '0','true, false', now())");
		run_sql("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Login Username', 'MODULE_PAYMENT_PLUGNPAY_LOGIN', 'Your Login Name', 'Enter your PlugnPay account username', '6', '0', now())");
		run_sql("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Publisher Email', 'MODULE_PAYMENT_PLUGNPAY_PUBLISHER_EMAIL', 'Enter Your Email Address', 'The email address you want PlugnPay conformations sent to', '6', '0', now())");
		run_sql("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, configuration_values, date_added) values ('Transaction Mode', 'MODULE_PAYMENT_PLUGNPAY_TESTMODE', 'Test', 'Transaction mode used for processing orders', '6', '0', 'Test, Test And Debug, Production', now())");
		run_sql("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, configuration_values, date_added) values ('Require CVV', 'MODULE_PAYMENT_PLUGNPAY_CVV', 'yes', 'Ask For CVV information', '6', '0', 'yes, no', now())");
		run_sql("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, configuration_values, date_added) values ('Transaction Method', 'MODULE_PAYMENT_PLUGNPAY_PAYMETHOD', 'credit', 'Transaction method used for processing orders.<br><b>NOTE:</b> Selecting \'onlinecheck\' assumes you\'ll offer \'credit\' as well.', '6', '0', 'credit, onlinecheck', now())");
		run_sql("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, configuration_values, date_added) values ('Authorization Type', 'MODULE_PAYMENT_PLUGNPAY_CCMODE', 'authpostauth', 'Credit card processing mode', '6', '0', 'authpostauth, authonly', now())");
		run_sql("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Sort Order Of Display', 'MODULE_PAYMENT_PLUGNPAY_SORT_ORDER', '1', 'The order in which this payment type is dislayed. Lowest is displayed first.', '6', '0' , now())");
		run_sql("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, configuration_values, date_added) values ('Customer Notifications', 'MODULE_PAYMENT_PLUGNPAY_DONTSNDMAIL', 'yes', 'Should PlugnPay not email a receipt to the customer?', '6', '0', 'yes, no', now())");
		run_sql("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, configuration_format, configuration_values, date_added) values ('Accepted Credit Cards', 'MODULE_PAYMENT_PLUGNPAY_ACCEPTED_CC', 'Mastercard, Visa', 'The credit cards you currently accept', '6', '0', 'multi_select', 'Amex, Discover, Mastercard, Visa', now())");
		run_sql("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, configuration_values, date_added) values ('Set Order Status', 'MODULE_PAYMENT_PLUGNPAY_ORDER_STATUS_ID', '0', 'Set the status of orders made with this payment module to this value', '6', '0', 'order_status_list()', now())");
	}

	function remove() {
		remove_module($this->module_key);
	}
}
?>
